const { Result } = require('../models/common');
const Router = require('koa-router'),
    // image = require('../images/'),
    // jwt = require('jsonwebtoken'),
    // {JWT_KEY} = require('../lib/constant.js'),
    // _ = require('lodash'),
    fs = require('fs'),
    mime = require('mime-types'),
    path = require('path'),
    router = new Router();
router.prefix('/api/image');

router.get('/:id', async (ctx, next) => {
    let file = null
    let { id } = ctx.params
    if (id === 'xxx') {
        id = 'a.png'
    }
    let filePath = `./images/${id}`
    try {
        file = fs.readFileSync(filePath)
    } catch (error) {
        console.log(error)
    }

    let mimeType = mime.lookup(filePath)
    ctx.set('content-type', mimeType)
    ctx.body = file
})
router.get('/2/:id', async (ctx, next) => {
    let file = null
    let { id } = ctx.params
    if (id === 'xxx') {
        id = 'a.png'
    }
    let filePath = `./images2/${id}`
    try {
        file = fs.readFileSync(filePath)
    } catch (error) {
        console.log(error)
    }

    let mimeType = mime.lookup(filePath)
    ctx.set('content-type', mimeType)
    ctx.body = file
})


router.post('/uploadfile/commodity', async (ctx, next) => {
    res = new Result()
    console.log(ctx.request)
    const file = ctx.request.files.File
    let fileext = `${file.type}`.split('/')
    let filename = `${(new Date().getTime()) + Math.round(Math.random() * 10000)}.${fileext[1]}`
    const reader = fs.createReadStream(`../../..${file.path}`)
    const upStream = fs.createWriteStream(`./images/${filename}`)
    reader.pipe(upStream)
    res.msg = '上传成功'
    res.data = filename
    ctx.body = res
})
router.post('/uploadfiles/commodity', async (ctx, next) => {
    res = new Result()
    const files = ctx.request.files.File
    let imagesname = []
    for (let file in files) {
        let fileext = `${files[file].type}`.split('/')
        let filename = `${(new Date().getTime()) + Math.round(Math.random() * 10000)}.${fileext[1]}`
        const reader = fs.createReadStream(`../../..${files[file].path}`)
        const upStream = fs.createWriteStream(`./images/${filename}`)
        reader.pipe(upStream)
        imagesname.push(`${filename}`)
    }
    res.msg = '上传成功'
    res.data = imagesname
    ctx.body = res
})
module.exports = router;
